package com.example.fw;

import org.netbeans.jemmy.operators.JDialogOperator;
import org.netbeans.jemmy.operators.JTextFieldOperator;
import org.netbeans.jemmy.operators.JTreeOperator;

import com.example.obj.FolderList;

public class FolderHelper extends HelperBase {

	private static FolderList folderCache;
	
	public FolderHelper(ApplicationManager manager) {
		super(manager);
	}

	public FolderList getFolders() {
		log.info("Get folder list");
		if (folderCache == null){
			buildFolderCache();
		}
		return folderCache;
	}

	private void buildFolderCache() {
		log.info("Build Folder Cache");
		folderCache = new FolderList();
		JTreeOperator tree = new JTreeOperator(manager.getApplication());
		Object[] children = tree.getChildren(tree.getRoot());
		for (Object child : children) {
			folderCache.add(child.toString());
		}
	}
	
	public String createFolder(String folderName) {		
		log.info("Add folder " + folderName + " to the list");		
		manager.getMenuHelper().pushCreateFolder();
		enterFolderName(folderName);
		pushButton("OK");
		String msg = waitMessageDialog("Warning", 1000);
		buildFolderCache();
		return msg;
	}

	private void enterFolderName(String folder) {
		JDialogOperator dialog = new JDialogOperator(manager.getApplication());
		new JTextFieldOperator(dialog).setText(folder);
	}

	public String deleteFolder(int i) {
		log.info("Delete folder " + i + ":" + getFolders().get(i) + " from the list");
		selectFolder(i);
		manager.getMenuHelper().pushDeleteFolder();
		pushButton("Yes");
		String msg = waitMessageDialog("Warning", 1000);
		buildFolderCache();
		return msg;
	}
	
	private void selectFolder(int i) {
		JTreeOperator tree = new JTreeOperator(manager.getApplication());
		tree.selectRow(i);
	}
}
